#include <users/userslist.h>
#include <fstream>
#include <iostream>
#include <sstream>

namespace users {
usersList::usersList(const std::filesystem::path& path, QObject *parent) : QObject{parent}{
	std::fstream file(path, std::ios::in | std::ios::out);
	if(file.is_open()) {
		std::string dataFromFile;
		std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(dataFromFile));
		std::istringstream iss(dataFromFile);
		std::string line;
		while (std::getline(iss, line)) {
			_users.emplace_back(line);
		}
	}
}

usersList::iterator usersList::begin() {
	return _users.begin();
}

usersList::iterator usersList::end() {
	return _users.end();
}

usersList::const_iterator usersList::begin() const {
	return _users.begin();
}

usersList::const_iterator usersList::end() const {
	return _users.end();
}

user &usersList::operator[](int index) {
	return _users[index];
}

void usersList::saveInFile(const std::filesystem::path& path) {
	std::string temp_filename = (std::filesystem::temp_directory_path() / "temp_fileXXXXXX").string();
	std::ofstream temp_file(temp_filename);

	if (temp_file.is_open()) {
		for(const auto& user : _users)
			temp_file << to_string(user) << "\n";
		temp_file.close();


		std::string existing_filename = path.string();


		if (std::filesystem::exists(existing_filename)) {
			std::filesystem::remove(existing_filename);
		}

		std::filesystem::rename(temp_filename, existing_filename);
	} else {
		throw std::runtime_error("Не могу открыть файл для записи");
	}

}

void usersList::appendUser(const user &user) {
	_users.push_back(user);
}

bool usersList::empty() const {
	return _users.empty();
}
}